package com.aiti.lulian.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.constant.MessageCodeConstant;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.utils.message.Message;
import com.aiti.framework.commons.dictmodel.entity.SysDictData;
import com.aiti.framework.commons.dictmodel.mapper.SysDictDataMapper;
import com.aiti.lulian.config.OCRConfig;
import com.aiti.lulian.dto.OcrBusinessLicenseDto;
import com.aiti.lulian.dto.RegisterEnterpriseInfoDto;
import com.aiti.lulian.dto.SearchDto;
import com.aiti.lulian.entity.*;
import com.aiti.lulian.entity.vr.EnterpriseVr;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.feign.ScaleEnterpriseService;
import com.aiti.lulian.mapper.*;
import com.aiti.lulian.ocr.BusinessLicenseResult;
import com.aiti.lulian.ocr.OcrService;
import com.aiti.lulian.service.EnterpriseInfoManageService;
import com.aiti.lulian.service.ILuLianEnterpriseMainIndustrySerivce;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.OcrInfoService;
import com.aliyun.teaopenapi.models.Config;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * description: 新的企业信息管理服务实现类
 * auth fcb
 * date 2025-04-23 17:41
 **/
@Service
@Slf4j
public class EnterpriseInfoManageServiceImpl implements EnterpriseInfoManageService {

    @Autowired
    private ILuLianEnterpriseUserService iLuLianEnterpriseUserService;
    @Autowired
    private LuLianEnterpriseUserMapper luLianEnterpriseUserMapper;
    @Autowired
    private LuLianEnterpriseHistoryMapper luLianEnterpriseHistoryMapper;
    @Autowired
    private LuLianEnterpriseMapper luLianEnterpriseMapper;
    @Autowired
    private LuLianEnterpriseProveMapper luLianEnterpriseProveMapper;
    @Autowired
    private ILuLianEnterpriseMainIndustrySerivce luLianEnterpriseMainIndustrySerivce;
    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;
    @Autowired
    private EnterpriseVrMapper enterpriseVrMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;
    @Autowired
    private ScaleEnterpriseService scaleEnterpriseService;
    @Autowired
    private OcrService ocrService;

    /**
     * 在注册成功之后填写一部分企业信息，填写这部分信息之后认为已经认证通过
     * 这里不再发送通知和写入搜索库
     * 原来的逻辑见{@link  LulianEnterpriseHistoryServiceImpl} yunZhanTingEnterpriseHistory
     * @param dto
     * @param userId
     */
    @Transactional(rollbackFor = Throwable.class)
    public void registerEnterpriseInfo(RegisterEnterpriseInfoDto dto) {
        // 1. 检验所有参数不能为空
        this.checkRegisterEnterpriseInfo(dto);
        Message usernameMsg = cloudShowManagerSubService.getUserIdByUserName(dto.getUsername());
        if(!Objects.equals(MessageCodeConstant.MSG_SUCCESS_CODE, usernameMsg.getCode())) {
            throw new BusinessException("根据注册手机号查询注册用户信息失败");
        }
        Map<String, String> userIdMap =(Map<String,String>)usernameMsg.getObj();
        String userId = userIdMap.get("userId");
        if(StrUtil.isBlank(userId)) {
            throw new BusinessException("根据注册手机号未查询到注册用户信息");
        }
        // 2. 检查企业是否已经存在
        Integer enterpriseUserCount = luLianEnterpriseUserMapper.selectEnterpriseCountByUserId(userId);
        if(enterpriseUserCount > 0) {
            throw new BusinessException("该用户已经关联企业，请勿重复关联");
        }
        Integer enterpriseHistoryCount = luLianEnterpriseHistoryMapper.selectCount(new QueryWrapper<LuLianEnterpriseHistory>().eq("unicode", dto.getUnicode()));
        if(enterpriseHistoryCount > 0) {
            throw new BusinessException("该企业【"+dto.getUnicode()+"】已经存在");
        }
        Integer enterpriseCount = luLianEnterpriseMapper.selectCount(new QueryWrapper<LuLianEnterprise>().eq("unicode", dto.getUnicode()));
        if(enterpriseCount > 0) {
            throw new BusinessException("该企业【"+dto.getUnicode()+"】在上线信息中已经存在，需核实");
        }
        // 3. 关联用户和企业
        String enterpriseId = IdUtil.simpleUUID();
        LuLianEnterpriseUser enterpriseUser = LuLianEnterpriseUser.builder().enterpriseId(enterpriseId).baseId(IdUtil.simpleUUID()).userId(userId).build();
        luLianEnterpriseUserMapper.insert(enterpriseUser);
        // 4. 插入数据到企业历史表
        LuLianEnterpriseHistory enterpriseHistory = this.buildEnterpriseHistory(dto, userId, enterpriseId);
        luLianEnterpriseHistoryMapper.insert(enterpriseHistory);
        // 5. 插入数据到企业认证表。自动认证通过
//        LuLianEnterprise luLianEnterprise = new LuLianEnterprise();
//        BeanUtil.copyProperties(enterpriseHistory,luLianEnterprise);
//        luLianEnterpriseMapper.insert(luLianEnterprise);
        // 6. 保存营业执照和行业门类
        LuLianEnterpriseProve luLianEnterpriseProve = LuLianEnterpriseProve.builder().baseId(IdUtil.simpleUUID()).enterpriseId(enterpriseId).businessLicenseUrl(dto.getBusinessLicenseUrl()).build();
        luLianEnterpriseProveMapper.insert(luLianEnterpriseProve);

        if(CollectionUtil.isNotEmpty(dto.getMainIndustrys())) {
            List<LuLianEnterpriseMainIndustry> mainIndustrys = dto.getMainIndustrys();
            for(LuLianEnterpriseMainIndustry mainIndustry : mainIndustrys) {
                mainIndustry.setBaseId(IdUtil.simpleUUID());
                mainIndustry.setEnterpriseId(enterpriseId);
            }
            luLianEnterpriseMainIndustrySerivce.saveBatch(mainIndustrys);
        }
        // 添加管理员角色，如果有个人角色，则将个人角色替换为企业管理员角色
        Map<String, String> params = new HashMap<>(16);
        params.put("userId", userId);
        params.put("roleId", "043ea2e3e02c4aa591df1f83e65069bc");
        Message me = cloudShowManagerSubService.addUserRoleNew(params);
        if(me.getCode().equals(MessageCodeConstant.MSG_FAIL_CODE)){
            throw new RuntimeException("保存用户角色失败");
        }
    }

    public void checkBusinessLicense(OcrBusinessLicenseDto dto) {
        BusinessLicenseResult result = ocrService.exeOcrBusinessLicenseService(dto);
        if(result.getData() == null) {
            throw new BusinessException("无法识别营业执照信息");
        }
        String creditCode = result.getData().getCreditCode();
        if(!dto.getUnicode().equals(creditCode)) {
            throw new BusinessException("营业执照信息与注册信息不一致");
        }
    }

    private LuLianEnterpriseHistory buildEnterpriseHistory(RegisterEnterpriseInfoDto dto, String userId, String enterpriseId) {
        LuLianEnterpriseHistory enterpriseHistory = new LuLianEnterpriseHistory();
        BeanUtil.copyProperties(dto,enterpriseHistory,"mainIndustrys","businessLicenseUrl");
        enterpriseHistory.setBaseId(enterpriseId);
        enterpriseHistory.setIsAuth(false);
        enterpriseHistory.setExamineStatus("");
        enterpriseHistory.setStatus("1");
        enterpriseHistory.setCreator(userId);
        enterpriseHistory.setBaseCreateTime(DateUtil.formatDateTime(new Date()));

        return enterpriseHistory;
    }

    private void checkRegisterEnterpriseInfo(RegisterEnterpriseInfoDto dto) {
        if(StrUtil.isEmpty(dto.getUsername())) {
            throw new BusinessException("参数错误，用户注册手机号不能为空");
        }
        if(StrUtil.isEmpty(dto.getBaseName())) {
            throw new BusinessException("参数错误，企业名称不能为空");
        }
        if(StrUtil.isEmpty(dto.getUnicode())) {
            throw new BusinessException("参数错误，统一社会信用代码/注册号不能为空");
        }
        if(StrUtil.isEmpty(dto.getRegisterType())) {
            throw new BusinessException("参数错误，企业类型不能为空");
        }
        if(CollectionUtil.isEmpty(dto.getMainIndustrys())) {
            throw new BusinessException("参数错误，企业门类不能为空");
        }
        if(StrUtil.isEmpty(dto.getProvince())) {
            throw new BusinessException("参数错误，所在地区省份不能为空");
        }
        if(StrUtil.isEmpty(dto.getCity())) {
            throw new BusinessException("参数错误，所在地区市不能为空");
        }
        if(StrUtil.isEmpty(dto.getCounty())) {
            throw new BusinessException("参数错误，所在地区县不能为空");
        }
        if(StrUtil.isEmpty(dto.getBusinessLicenseUrl())) {
            throw new BusinessException("参数错误，营业执照不能为空");
        }
    }

}
